/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <stdio.h>
#include "Xern/IInputSystem.hpp"
#include "Xern/IGuiSystem.hpp"
#include "Xern/Engine.hpp"
#include "Xern/KeyCode.hpp"

#include "InputController.hpp"
#include "ClientModule.hpp"

const float MouseScale = 0.001f;

namespace XernClient
{
	InputController::InputController()
	{
		enabled = false;
		mouseX = mouseY = mouseZ = -1;
	}

	InputController::~InputController()
	{
	}

	void InputController::Initialize()
	{
		boost::shared_ptr<IInputSystem> input = Engine::Get().GetInputSystem();
		if(input)
			input->RegisterListener(shared_from_this());
	}

	void InputController::Shutdown()
	{
		boost::shared_ptr<IInputSystem> input = Engine::Get().GetInputSystem();
		if(input)
			input->UnregisterListener(shared_from_this());
		playerEntity.reset();
	}

	void InputController::Activate()
	{
		// Hide the gui.
		boost::shared_ptr<IGuiSystem> gui = Engine::Get().GetGuiSystem();
		gui->Hide();

		// Set enabled flag.
		enabled = true;
	}

	void InputController::Deactivate()
	{
		// Show the gui.
		boost::shared_ptr<IGuiSystem> gui = Engine::Get().GetGuiSystem();
		gui->Show();

		// Set enabled flag.
		enabled = false;
	}

	void InputController::MouseMoved(int x, int y, int z)
	{
		char msg[64];
		if(!enabled)
		{
			mouseX = x; mouseY = y; mouseZ = z;
			return;
		}

		if(mouseX < 0)
			mouseX = x;
		if(mouseY < 0)
			mouseY = y;
		if(mouseZ < 0)
			mouseZ = z;

		int dx = x - mouseX;
		int dy = y - mouseY;
		int dz = z - mouseZ;

		Vector3 deltaAngle(dy, dx, dz);
		deltaAngle *= MouseScale;
		angle += deltaAngle;

		if(playerEntity)
			UpdateAngle();

		mouseX = x; mouseY = y; mouseZ = z;
	}

	void InputController::MousePressed(int x, int y, unsigned int button)
	{
		mouseX = x; mouseY = y;
		if(!enabled)
			return;

		switch(button)
		{
		case MB_LEFT:
			if(playerEntity)
				playerEntity->OnEvent("fire", "LocalClient", "1");
			break;
		case MB_RIGHT:
			if(playerEntity)
				playerEntity->OnEvent("fire2", "LocalClient", "1");
			break;
		default:
			break;
		}
	}

	void InputController::MouseReleased(int x, int y, unsigned int button)
	{
		mouseX = x; mouseY = y;
		if(!enabled)
			return;
	}

	void InputController::KeyPressed(unsigned int key, unsigned int text)
	{
		// The escape key is special.
		if(key == KC_ESCAPE)
		{
			if(enabled)
				Deactivate();
			else
				Activate();
		}

		if(!enabled)
			return;

		KeyChange(key, true);
	}

	void InputController::KeyReleased(unsigned int key)
	{
		if(!enabled)
			return;

		KeyChange(key, false);
	}

	void InputController::KeyChange(unsigned int key, bool state)
	{
		char data[64];
		sprintf(data, "%d", state);

		switch(key)
		{
		case KC_W:
			if(playerEntity)
				playerEntity->OnEvent("forward", "LocalClient", data);
			break;
		case KC_S:
			if(playerEntity)
				playerEntity->OnEvent("backward", "LocalClient", data);
			break;
		case KC_A:
			if(playerEntity)
				playerEntity->OnEvent("left", "LocalClient", data);
			break;
		case KC_D:
			if(playerEntity)
				playerEntity->OnEvent("right", "LocalClient", data);
			break;
		case KC_LSHIFT:
			if(playerEntity)
				playerEntity->OnEvent("sprint", "LocalClient", data);
			break;
		case KC_SPACE:
			if(playerEntity)
				playerEntity->OnEvent("jump", "LocalClient", data);
			break;

		case KC_LEFT:
			if(state)
				angularVelocity.y = -1.0f;
			else if (!state && CompareFloat(angularVelocity.y, -1.0f)== 0)
				angularVelocity.y = 0.0f;
			break;
		case KC_RIGHT:
			if(state)
				angularVelocity.y = 1.0f;
			else if (!state && CompareFloat(angularVelocity.y, 1.0f)== 0)
				angularVelocity.y = 0.0f;
			break;
		case KC_PGUP:
			if(state)
				angularVelocity.x = -1.0f;
			else if (!state && CompareFloat(angularVelocity.x, -1.0f)== 0)
				angularVelocity.x = 0.0f;
			break;
		case KC_PGDOWN:
			if(state)
				angularVelocity.x = 1.0f;
			else if (!state && CompareFloat(angularVelocity.x, 1.0f)== 0)
				angularVelocity.x = 0.0f;
			break;
		default:
			// Ignore the key.
			break;
		}
	}

	void InputController::Think(float delta)
	{
		if(playerEntity && CompareFloat(angularVelocity.Length2(), 0.0) == 0)
			return;

		angle += angularVelocity.Normalize()*delta*2.0f;
		UpdateAngle();

	}

	void InputController::UpdateAngle()
	{
		char msg[64];

		if(!playerEntity)
			return;

		if(angle.x > X_PI_2)
			angle.x = X_PI_2;
		else if(angle.x < -X_PI_2)
			angle.x = -X_PI_2;

		orientation = Quaternion(angle.x, angle.y, angle.z).Conjugate();
		sprintf(msg, "%f %f %f %f",
				orientation.w, orientation.x, orientation.y, orientation.z);
		playerEntity->OnEvent("orientation", "LocalClient", msg);
		ClientModule::Get().AngleChange(orientation);
	}

	void InputController::SetPlayerEntity(boost::shared_ptr<Entity> ent)
	{
		playerEntity = ent;
		angle = Vector3(0.0f);
		orientation = Quaternion();
	}
}; // namespace XernClient
